package com.hdjd.service.imp;

import com.hdjd.dao.*;
import com.hdjd.entities.*;
import com.hdjd.service.AccountService;
import com.hdjd.util.FileAccImgUpload;
import com.hdjd.util.FileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class AccountServiceImp implements AccountService {

    @Autowired
    private AccountDao accountDao;

    @Autowired
    private AdminDao adminDao;
    @Autowired
    private FundRecordDao fundRecordDao;
    @Autowired
    private ReceiveAddressDao receiveAddressDao;
    @Autowired
    private OpinionDao opinionDao;
    @Autowired
    private OpinionFileDao opinionFileDao;
    @Autowired
    private SchoolDao schoolDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private OrderDetailDao orderDetailDao;

    @Override
    public Object selectAccountByStuNoOrAccNameAndAccPwd(String stuNo, String accName, String accPwd) {
            try{
                Account account = this.accountDao.selectAccountByStuNoOrAccNameAndAccPwd(stuNo,accName,accPwd);
                Admin admin = this.adminDao.selectAdminByAdminNameAndAdminPwd(accName,accPwd);
                School schoolUser = this.schoolDao.selectSchoolBySchAccNameAndAccPwd(accName, accPwd);
                if (admin != null){
                    return admin;
                }
                if (schoolUser != null) {
                    return schoolUser;
                }
                if (account != null){
                    School school = this.schoolDao.selectSchoolBySchoolId(account.getSchoolId());
                    if (school.getSchStatus()==0){
                        return -1;
                    }
                    return account;
                }

            }catch (Exception e){
                e.printStackTrace();
                return null;
            }
        return null;
    }

    @Override
    public boolean registerDeliverymanByAccId(Integer accId) {
        Account account = new Account();
        account.setAccId(accId);
        account.setDeliverymanSign(1);
        boolean flag = false;
        try{
            flag = this.accountDao.updateAccountByAccId(account);
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }

    @Override
    public boolean withdrawByAccIdAndAccPwd(Integer accId, String accPwd, double money) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (money <= 0){
            throw new RuntimeException("输入的金额有误");
        }
        Account account = this.accountDao.selectAccountByAccIdAndAccPwd(accId,accPwd);
        if (account == null){
            throw new RuntimeException("密码错误");
        }
        double accBalance = account.getAccBalance() - money;
        if (accBalance < 0){
            throw new RuntimeException("账户余额不足提现失败");
        }
        account.setAccBalance(accBalance);
        this.accountDao.updateByPrimaryKey(account);
        FundRecord fundRecord = new FundRecord();
        fundRecord.setAccId(accId);
        fundRecord.setAddTime(sdf.format(new Date()));
        fundRecord.setDealAmount(money);
        fundRecord.setRecordBalance(accBalance);
        fundRecord.setRecordType(2);
        return this.fundRecordDao.insertFundRecord(fundRecord);
    }

    @Override
    public boolean toUPByAccIdAndAccPwd(Integer accId, double money) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (money <= 0){
            throw new RuntimeException("输入的金额有误");
        }
        Account account = this.accountDao.selectAccountByAccId(accId);
        double accBalance = account.getAccBalance() + money;
        account.setAccBalance(accBalance);
        this.accountDao.updateByPrimaryKey(account);
        FundRecord fundRecord = new FundRecord();
        fundRecord.setAccId(accId);
        fundRecord.setAddTime(sdf.format(new Date()));
        fundRecord.setDealAmount(money);
        fundRecord.setRecordBalance(accBalance);
        fundRecord.setRecordType(1);
        return this.fundRecordDao.insertFundRecord(fundRecord);
    }

    @Override
    public String selectAccBalanceByAccId(Integer accId) {
        DecimalFormat df = new DecimalFormat("###,##0.00");
        df.setMaximumFractionDigits(2);
        return df.format(this.accountDao.selectAccBalanceByAccId(accId));
    }

    @Override
    public List<FundRecord> selectFundRecordByAccId(Integer accId, String startDate, String endDate, Integer pageCurrent, Integer pageSize) {
        String[] dates = endDate.split("-");
        Integer date = Integer.parseInt(dates[2]) + 1;
        endDate = dates[0]+'-'+dates[1]+'-'+date;
        List<FundRecord> fundRecordList = this.fundRecordDao.selectFundRecordByAccId(accId, startDate, endDate, (pageCurrent-1)*pageSize, pageSize);
        return fundRecordList;
    }

    @Override
    public Account selectAccountByAccId(Integer accId) {
        return this.accountDao.selectAccountByAccId(accId);
    }

    @Override
    public int editAccountByAccount(Integer accId, MultipartFile accImg,String accTruename,Integer accSex,
                                    String accTelephone, String accEmail, String accBirthday, HttpServletRequest request) {
        Account account = this.accountDao.selectAccountByAccId(accId);
        String imgUrl = null;
        if (accImg != null){
            try {
                //调用util包中文件上传类(FileUpload)中方法，将上传的图片保存到本地，并返回图片新名称
                imgUrl = FileAccImgUpload.fileUpload(accImg, request);
            } catch (Exception e) {
                throw new RuntimeException("图片保存失败");
            }
        }
        account.setAccImg(imgUrl);
        account.setAccTruename(accTruename);
        account.setAccSex(accSex);
        account.setAccTelephone(accTelephone);
        account.setAccEmail(accEmail);
        account.setAccBirthday(accBirthday);
        return this.accountDao.updateByPrimaryKeySelective(account);
    }

    @Override
    public List<ReceiveAddress> selectReceiveAddressByAccId(Integer accId) {
        return this.receiveAddressDao.selectReceiveAddressByAccId(accId);
    }

    @Override
    public ReceiveAddress selectDefaultReceiveAddressByAccId(Integer accId) {
        return this.receiveAddressDao.getDefaultReceiveAddressByAccId(accId);
    }

    @Override
    public ReceiveAddress selectReceiveAddressByReAddressId(Integer reAddressId) {
        return this.receiveAddressDao.selectByPrimaryKey(reAddressId);
    }

    @Transactional
    @Override
    public int opinionGoods(Integer opiId, Integer detId, Integer goId, String goNm, Integer accId, String opiType, String opiContent,HttpServletRequest request) {
        //评价信息插入或者更新
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Opinion opinion = this.opinionDao.selectOpinionByDetId(detId);
        if (opinion == null){
            opinion = new Opinion();
            opinion.setDetId(detId);
        }else {
            if (opiId != null){
                opinion.setOpiId(opiId);
                opinion.setAccId(accId);
                opinion.setOpiType(opiType);
                opinion.setOpiTime(sdf.format(new Date()));
                opinion.setOpiContent(opiContent);
                opinion.setGoId(goId);
                opinion.setGoNm(goNm);
            }
        }

        if (accId != null){
            this.opinionDao.updateByPrimaryKeySelective(opinion);
            //修改订单状态为已评价
            OrderDetail orderDetail = this.orderDetailDao.selectOrderDetailByDetId(detId);
            orderDetail.setOrdStatus("6");
            this.orderDetailDao.updateOrderDetailByDetId(orderDetail);
            return 1;
        }else {
            if (opinion.getOpiId() == null){
                this.opinionDao.insertSelective(opinion);
            }
            return opinion.getOpiId();
        }
    }

    @Override
    public List<Map<String,Object>> selectMyOpinion(Integer accId, Integer pageCurrent, Integer pageSize) {
        List<Opinion> opinions = this.opinionDao.selectOpinionByAccId(accId,(pageCurrent-1)*pageSize,pageSize);
        List<Map<String,Object>> mapList = new ArrayList<>();
        for (Opinion opinion : opinions) {
            opinion.setOpinionFile(this.opinionFileDao.selectOpinionFile(opinion.getOpiId()));
            Goods goods = this.goodsDao.selectGoodsByGoId(opinion.getGoId());
            Map<String,Object> map = new HashMap<>();
            map.put("opinion",opinion);
            map.put("goods",goods);
            mapList.add(map);
        }
        return mapList;
    }
    @Override
    public int selectMyOpinionNum(Integer accId) {
        return this.opinionDao.selectOpinionNumByAccId(accId);
    }

    @Override
    public Opinion selectMyOpinionByDetId(Integer detId) {
        return this.opinionDao.selectOpinionByDetId(detId);
    }

    @Override
    public int deleteMyOpinion(Integer opiId) {
        this.opinionFileDao.deleteOpinionFileByOpiId(opiId);
        this.opinionDao.deleteByPrimaryKey(opiId);
        return 1;
    }

    @Override
    public Integer selectCountFundRecordByAccId(Integer accId, String startDate, String endDate) {
        String[] dates = endDate.split("-");
        Integer date = Integer.parseInt(dates[2]) + 1;
        endDate = dates[0]+'-'+dates[1]+'-'+date;
        return this.fundRecordDao.selectCountFundRecordByAccId(accId, startDate, endDate);
    }

    @Override
    public int updateMyReAddress(ReceiveAddress receiveAddress) {
        return this.receiveAddressDao.updateByPrimaryKeySelective(receiveAddress);
    }

    @Override
    public int deleteMyReAddress(Integer reAddressId) {
        return this.receiveAddressDao.deleteByPrimaryKey(reAddressId);
    }

    @Override
    public int updateMyReAddressDefault(Integer accId, Integer reAddressId) {
        List<ReceiveAddress> receiveAddressList = this.receiveAddressDao.selectReceiveAddressByAccId(accId);
        for (ReceiveAddress receiveAddress : receiveAddressList) {
            if (receiveAddress.getReAddressId() != reAddressId){
                receiveAddress.setReDefaultAddress(0);

            }else {
                receiveAddress.setReDefaultAddress(1);
            }
            this.receiveAddressDao.updateByPrimaryKeySelective(receiveAddress);
        }
        return 1;
    }

    @Override
    public int addMyReAddress(ReceiveAddress receiveAddress) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        receiveAddress.setAddTime(sdf.format(new Date()));
        receiveAddress.setReDefaultAddress(0);
        return this.receiveAddressDao.insert(receiveAddress);
    }

    //用户注册，新增用户
    @Override
    public boolean insertAccount(Account account) {
        boolean flag = false;
        if(account != null){
            flag = this.accountDao.insertAccount(account);
        }
        return flag;
    }

    @Override
    public boolean selectAccountByAccName(String accName) {
        Account account = null;
        boolean flag = false;
        if(accName != null && !("").equals(accName)){
            account = this.accountDao.selectAccountByAccName(accName);
        }
        //如果 account 不为 null，说明用户名已存在
        if(account != null){
            flag = true;
        }
        return flag;
    }

    @Override
    public List<String> selectOpinionFile(Integer opiId) {
        return this.opinionFileDao.selectOpinionFile(opiId);
    }
}
